import { resolve } from 'path';
import { defineConfig, loadEnv } from 'vite';
import { createHtmlPlugin } from 'vite-plugin-html';
import vue from '@vitejs/plugin-vue';

import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';

import { createSvgIconsPlugin } from 'vite-plugin-svg-icons';

import VueSetupExtend from 'vite-plugin-vue-setup-extend';

import { VantResolver } from '@vant/auto-import-resolver';

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd());
  let buildParams: any;
  if (env.VITE_APP_BUILD_MODE === 'lib') {
    buildParams = {
      outDir: 'uniChatLib',
      lib: {
        entry: resolve(__dirname, 'src/lib/index.ts'),
        formats: ['es', 'cjs', 'umd'],
        fileName: 'unichat-visitor',
        name: 'unichat-visitor'
      },
      assetsInclude: ['**/*.mp3'] // 确保包括 mp3 文件
    };
  } else {
    buildParams = {
      outDir: 'dist'
    };
  }
  const rollupOptions: any = {};
  if (env.VITE_APP_INCLUDE_TEST_PAGE == '0') {
    rollupOptions.exclude = ['src/views/login/login.vue'];
    buildParams.rollupOptions = rollupOptions;
  }

  return {
    build: buildParams,
    base: "./",
    plugins: [
      vue(),
      VueSetupExtend(),
      AutoImport({
        resolvers: [ElementPlusResolver(), VantResolver()]
      }),
      Components({
        resolvers: [ElementPlusResolver(), VantResolver()]
      }),
      createSvgIconsPlugin({
        iconDirs: [resolve(__dirname, 'src/assets/icons/svg')],
        symbolId: 'icon-[name]'
      }),
      createHtmlPlugin({
        minify: true,
        inject: {
          data: {
            apiURL: loadEnv(mode, process.cwd()).VITE_APP_API,
            socketURL: loadEnv(mode, process.cwd()).VITE_APP_SOCKET,
            title: ''
          }
        }
      }),
    ],
    resolve: {
      alias: {
        '@': resolve(__dirname, './src')
      }
    },
    server: {
      host: '0.0.0.0'
    }
  };
});
